package com.work.formaldehyde.activity;

import android.app.Activity;
import android.app.ActivityOptions;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.umeng.analytics.MobclickAgent;
import com.work.formaldehyde.R;
import com.work.formaldehyde.activityadapter.JianCeZuoAdapter;
import com.work.formaldehyde.activityadapter.QuXiaoDingDanAdapter;
import com.work.formaldehyde.orderfragment.AllFragment;
import com.work.formaldehyde.util.ApiUtils;
import com.work.formaldehyde.util.AppManager;
import com.work.formaldehyde.util.Url;

import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;


public class QuXiaoDingDanActivity extends Activity implements View.OnClickListener {
    private File fl;
    private ImageView comeback, loction_xia_img_one, gouwuche_img;
    private LinearLayout addimg;
    private RelativeLayout fankui_tijiao, kqr;
    private String url = "";
    private RelativeLayout dianji, one;
    private TextView gouwuche_money, shangpingmingzi, gouwuche_manjian_text,quxiaoyuanyin;
    private EditText beizhu;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ApiUtils.ActivityIsLogin(this, 1);
        AppManager.getAppManager().addActivity(this);
        setContentView(R.layout.activity_quxiaodingdan);
        comeback = findViewById(R.id.querendingdan_comeback);
        comeback.setOnClickListener(this);
        if (ApiUtils.isNetworkConnected(QuXiaoDingDanActivity.this))
            init();
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    private String moneyall, dingdanhao, shangpingname, shangpingnum;

    /**
     * 初始加载
     */
    public void init() {
        Intent getstr = getIntent();
        moneyall = getstr.getStringExtra("dingdanallmoney");
        dingdanhao = getstr.getStringExtra("dingdannum");
        shangpingname = getstr.getStringExtra("shangpingname");
        shangpingnum = getstr.getStringExtra("shangpingnum");
        quxiaoyuanyin=findViewById(R.id.quxiaoyuanyin);
        quxiaoyuanyin.setText("取消订单原因:"+tuihuangliyou);
        gouwuche_img = findViewById(R.id.gouwuche_img);
        beizhu = findViewById(R.id.beizhu);
        ApiUtils.GET_IMAGE(QuXiaoDingDanActivity.this, getstr.getStringExtra("shangpingimg"), gouwuche_img);
        shangpingmingzi = findViewById(R.id.shangpingmingzi);
        shangpingmingzi.setText(shangpingname);
        gouwuche_manjian_text = findViewById(R.id.gouwuche_manjian_text);
        gouwuche_manjian_text.setText("x" + shangpingnum);
        gouwuche_money = findViewById(R.id.gouwuche_money);
        gouwuche_money.setText(moneyall + "元");
        kqr = findViewById(R.id.kqr);
        kqr.setOnClickListener(this);
        loction_xia_img_one = findViewById(R.id.loction_xia_img_one);
        addimg = findViewById(R.id.addimg);
        one = findViewById(R.id.one);
        one.setOnClickListener(this);
        fankui_tijiao = findViewById(R.id.fankui_tijiao);
        fankui_tijiao.setOnClickListener(this);
        Init();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.fankui_tijiao:
                ApiUtils.windows(QuXiaoDingDanActivity.this, fankui_tijiao, "取消中");
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        ApiUtils.closepopup();
                    }
                }, 10000);
                postfile(filesa);
//                okHttp_postFromParameters();
                break;
            case R.id.querendingdan_comeback:
                onBackPressed();
                break;
            case R.id.one:
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent, 2);
                break;

            case R.id.kqr:
                loction_xia_img_one.setPivotX(loction_xia_img_one.getWidth() / 2)
                ;
                loction_xia_img_one.setPivotY(loction_xia_img_one.getHeight() / 2);
                if (kq) {
                    loction_xia_img_one.animate().rotation(180);
                    kq = false;
                    windows(QuXiaoDingDanActivity.this);
                }
                break;
        }
    }

    public boolean onKeyUp(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                onBackPressed();
                break;
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (index == 3) {
            one.setVisibility(View.GONE);
        }
    }

    private int index = 0;
    public File filesa;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2) {
            // 从相册返回的数据
            if (data != null) {
                // 得到图片的全路径
                Uri uri = data.getData();
                int w = one.getMeasuredWidth();
                int h = one.getMeasuredHeight();
                ImageView imageView = new ImageView(QuXiaoDingDanActivity.this);
                LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(w, h);
                lp1.setMargins(24, 0, 0, 0);
                imageView.setLayoutParams(lp1);
                imageView.setImageURI(uri);
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                addimg.addView(imageView);
                url = uri.toString();
                index++;
                one.setVisibility(View.GONE);
                filesa = uri2File(uri);
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String picPath = cursor.getString(columnIndex);
                //转码
                try {
                    String encode = URLEncoder.encode(picPath, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                cursor.close();
                if (picPath.equals("")) return;
            }
        }
    }

    private QuXiaoDingDanAdapter jianCeJiLuAdapter;
    private ArrayList<String> zhuwolist = new ArrayList<>();

    public void Init() {
        for (int is = 0; is < 6; is++) {
            if (is == 0) {
                zhuwolist.add("2");
            }
            zhuwolist.add("1");
        }
        jianCeJiLuAdapter = new QuXiaoDingDanAdapter(zhuwolist,
                QuXiaoDingDanActivity.this);
    }

    private Boolean kq = true;
    private PopupWindow popupWindows;
    private String tuihuangliyou = "七天无理由退货";

    public void windows(Context context) {
        View popupwindowviews = LayoutInflater.from(context).inflate(
                R.layout.popupwindow_quxiao, null);
        final ListView zhuwo_check_list = popupwindowviews.findViewById(R.id.zhuwo_check_list);
        zhuwo_check_list.setAdapter(jianCeJiLuAdapter);
        zhuwo_check_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                for (int is = 0; is < zhuwolist.size(); is++) {
                    if (zhuwolist.get(is).equals("2") && is != i) {
                        zhuwolist.set(is, "1");
                    }
                }
                zhuwolist.set(i, "2");
                jianCeJiLuAdapter.notifyDataSetChanged();
                switch (i) {
                    case 0:
                        tuihuangliyou = "七天无理由退货";
                        quxiaoyuanyin.setText("取消订单原因:"+tuihuangliyou);
                        popupWindows.dismiss();
                        break;
                    case 1:
                        tuihuangliyou = "收到商品破损";
                        quxiaoyuanyin.setText("取消订单原因:"+tuihuangliyou);
                        popupWindows.dismiss();
                        break;
                    case 2:
                        tuihuangliyou = "商品错发/漏发";
                        quxiaoyuanyin.setText("取消订单原因:"+tuihuangliyou);
                        popupWindows.dismiss();
                        break;
                    case 3:
                        tuihuangliyou = "未按约定时间发货";
                        quxiaoyuanyin.setText("取消订单原因:"+tuihuangliyou);
                        popupWindows.dismiss();
                        break;
                    case 4:
                        tuihuangliyou = "商品质量有问题";
                        quxiaoyuanyin.setText("取消订单原因:"+tuihuangliyou);
                        popupWindows.dismiss();
                        break;
                    case 5:
                        tuihuangliyou = "商品拍错了";
                        quxiaoyuanyin.setText("取消订单原因:"+tuihuangliyou);
                        popupWindows.dismiss();
                        break;
                    case 6:
                        tuihuangliyou = "其他";
                        quxiaoyuanyin.setText("取消订单原因:"+tuihuangliyou);
                        popupWindows.dismiss();
                        break;
                }
            }
        });
        popupWindows = new PopupWindow(popupwindowviews, (getWindowManager().getDefaultDisplay().getWidth()) * 2 / 5,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindows.setTouchable(true);
        popupWindows.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // TODO Auto-generated method stub
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
                loction_xia_img_one.animate().rotation(360);
                kq = true;
            }
        });
        popupWindows.setFocusable(true);
        popupWindows.setOutsideTouchable(true);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.4f;
        getWindow().setAttributes(lp);
        popupWindows.showAsDropDown(loction_xia_img_one, -0, 0, Gravity.LEFT);
    }

    /**
     * user转换为file文件
     * 返回值为file类型
     *
     * @param uri
     * @return
     */
    private File uri2File(Uri uri) {
        String img_path;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor actualimagecursor = managedQuery(uri, proj, null,
                null, null);
        if (actualimagecursor == null) {
            img_path = uri.getPath();
        } else {
            int actual_image_column_index = actualimagecursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            actualimagecursor.moveToFirst();
            img_path = actualimagecursor
                    .getString(actual_image_column_index);
        }
        File file = new File(img_path);
        return file;
    }

    public void postfile(final File file) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");
                    RequestBody requestBody;
                    if(file!=null) {
                        requestBody = new MultipartBody.Builder()
                                .setType(MultipartBody.FORM)
                                .addFormDataPart("uid", Url.USER_ID)
                                .addFormDataPart("logintoken", Url.LOGIN_TOKEN)
                                .addFormDataPart("order_number", dingdanhao)
                                .addFormDataPart("return_money", moneyall)
                                .addFormDataPart("return_cause", beizhu.getText().toString()).addFormDataPart("return_explain", tuihuangliyou)
                                .addFormDataPart("images", file.getName(), RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
                                .build();
                    }else{
                        requestBody = new MultipartBody.Builder()
                                .setType(MultipartBody.FORM)
                                .addFormDataPart("uid", Url.USER_ID)
                                .addFormDataPart("logintoken", Url.LOGIN_TOKEN)
                                .addFormDataPart("order_number", dingdanhao)
                                .addFormDataPart("return_money", moneyall)
                                .addFormDataPart("return_cause", beizhu.getText().toString()).addFormDataPart("return_explain", tuihuangliyou)
                                .addFormDataPart("images", "")
                                .build();
                    }
                    Request request = new Request.Builder()
                            .url(Url.TUIKUAN)
                            .post(requestBody)
                            .build();
                    okhttp3.Response response = okHttpClient.newCall(request).execute();
                    String msg = response.body().string();
                    Message message = new Message();
                    message.obj = msg;
                    gethot.sendMessage(message);
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void okHttp_postFromParameters() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    RequestBody formBody = new FormBody.Builder()
                            .add("uid", Url.USER_ID).add("logintoken", Url.LOGIN_TOKEN).add("order_number", dingdanhao).add("return_money", moneyall).add("return_cause", beizhu.getText().toString()).add("return_explain", tuihuangliyou).add("images", url).build();
                    Request request = new Request.Builder().url(Url.TUIKUAN).post(formBody).build();
                    okhttp3.Response response = okHttpClient.newCall(request).execute();
                    String msg = response.body().string();
                    Message message = new Message();
                    message.obj = msg;
                    gethot.sendMessage(message);
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).
                start();
    }

    public Handler gethot = new Handler() {
        public void handleMessage(android.os.Message msg) {
            JSONObject success_Object;
            try {
                if (msg.obj != null) {
                    ApiUtils.closepopup();
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    String msgs = success_Object.getString("msg");
                    if (code.equals("1")) {
                        AllFragment.tuikuanok=true;
                        ApiUtils.SetToast(QuXiaoDingDanActivity.this,"申请成功");
                        AppManager.getAppManager().finishActivity(DingDanXiangQingActivity.class);
                        onBackPressed();
                    }else{
                        ApiUtils.SetToast(QuXiaoDingDanActivity.this,msgs);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

}
